import matplotlib.pyplot as plt
from sklearn import datasets
from sklearn.decomposition import PCA
from sklearn.manifold import TSNE
import umap
# 配置中文字体
plt.rcParams['font.sans-serif'] = ['SimHei', 'Heiti TC', 'STHeiti']  # 支持中文显示
plt.rcParams['axes.unicode_minus'] = False  # 解决负号显示问题
# 加载数据
iris = datasets.load_iris()
X, y = iris.data, iris.target

# 创建降维模型
pca = PCA(n_components=2)
tsne = TSNE(n_components=2, perplexity=30, random_state=42)
umap_model = umap.UMAP(n_neighbors=15, min_dist=0.1, random_state=42)

# 应用降维
X_pca = pca.fit_transform(X)
X_tsne = tsne.fit_transform(X)
X_umap = umap_model.fit_transform(X)

# 可视化
plt.figure(figsize=(18, 5))

plt.subplot(131)
plt.scatter(X_pca[:, 0], X_pca[:, 1], c=y, cmap='viridis', edgecolor='k')
plt.title('PCA - 鸢尾花数据集')
plt.xlabel('主成分1')
plt.ylabel('主成分2')

plt.subplot(132)
plt.scatter(X_tsne[:, 0], X_tsne[:, 1], c=y, cmap='viridis', edgecolor='k')
plt.title('t-SNE - 鸢尾花数据集')
plt.xlabel('t-SNE维度1')
plt.ylabel('t-SNE维度2')

plt.subplot(133)
plt.scatter(X_umap[:, 0], X_umap[:, 1], c=y, cmap='viridis', edgecolor='k')
plt.title('UMAP - 鸢尾花数据集')
plt.xlabel('UMAP维度1')
plt.ylabel('UMAP维度2')

plt.tight_layout()
plt.savefig('dimension_reduction_comparison.png', dpi=300)
plt.show()